﻿
using BLE_Barcode;
using DevComponents.DotNetBar;
using Entity;
using Matter_Barcode;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Win32;
using Newtonsoft.Json;
using Public;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Media;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static Check_Barcode.Frm_main;
using Application = System.Windows.Forms.Application;
using DataTable = System.Data.DataTable;

namespace Check_Barcode
{
    public partial class Frm_main : DevComponents.DotNetBar.Office2007Form
    {
        const uint KEYEVENTF_EXTENDEDKEY = 0x1;
        const uint KEYEVENTF_KEYUP = 0x2;

        [DllImport("user32.dll")]
        static extern short GetKeyState(int nVirtKey);
        [DllImport("user32.dll")]
        static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);

        public enum VirtualKeys : byte
        {
            VK_NUMLOCK = 0x90, //数字锁定键
            VK_SCROLL = 0x91,  //滚动锁定
            VK_CAPITAL = 0x14, //大小写锁定
            VK_A = 62
        }
        public Frm_main()
        {
            InitializeComponent();            

        }
        static SerialPort sp1 = new SerialPort();
        static MySQLHelper DBhelper;
        string barcodeRule;
        string softTile;
        string cmb_printType;
        int skin;
        int handleError;
        string unlockPwd;
        int cmb_Separator;
        string checkCuplicate;
        string _条码规则, _条码规则2, _是否播放PASS声音, _是否播放NG声音, _模式, _ONLY_SCAN, _标题, _SN1标题, _SN2标题;

        string unlock_pwd;
        string urlPrefix;
        string _批次号;
        string _USER;
        string _PortName;
        int _input_type, _BaudRate;
        string OKSoundFilePath = Application.StartupPath + @"\Sound\ok.wav";//ok声音
        string NGSoundFilePath = Application.StartupPath + "\\Sound\\no1.wav";//NG声音

        bool print1Flag, print2Flag;
        string TemplatePath = "", TemplatePath2;      
        string comboBox_printer1, comboBox_printer2;
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        private Thread threadPause;
        Microsoft.Extensions.Caching.Memory.MemoryCache cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());
        SoftReg softReg = new SoftReg();
        //控制循环搜索
        private System.Windows.Forms.Timer timerLoopSearch;
        private bool isLoopSearching = false;

        string getDeviceAddress = "";
        // 在类中添加搜索开始时间的字段
        private DateTime _searchStartTime;

        //SerialPort sp1 = new SerialPort();
        BarTender_Print barTender = null;
        // 检查指定名称的进程是否正在运行
        static bool IsProcessRunning(string processName)
        {
            Process[] processes = Process.GetProcessesByName(processName);
            return processes.Length > 0;
        }

        #region 读取ini配置文件
        public void ReadConfig()
        {
            try
            {
                string ConString = ConfigurationManager.AppSettings["Connectionstring"];
                string softTile = ConfigurationManager.AppSettings["softTile"];

                barcodeRule = ConfigurationManager.AppSettings["barcodeRule"] + "";
                cmb_Separator = Convert.ToInt32(ConfigurationManager.AppSettings["cmb_Separator"]);
                
                print1Flag = ConfigurationManager.AppSettings["print1Flag"]=="Y" ? true : false;
                print2Flag = ConfigurationManager.AppSettings["print2Flag"] == "Y" ? true : false;

                TemplatePath = ConfigurationManager.AppSettings["TemplatePath"] + "";
                TemplatePath2 = ConfigurationManager.AppSettings["TemplatePath2"] + "";

                comboBox_printer1 = ConfigurationManager.AppSettings["comboBox_printer1"];
                comboBox_printer2 = ConfigurationManager.AppSettings["comboBox_printer2"];
                skin = Convert.ToInt32(ConfigurationManager.AppSettings["skin"]);
                handleError = Convert.ToInt32(ConfigurationManager.AppSettings["handleError"]);

                this.TitleText = softTile;
                this.Text = softTile;
                label4.Text = softTile;
                label_barcode1.Text = ConfigurationManager.AppSettings["label_barcode1"] + "";
                label_barcode2.Text = ConfigurationManager.AppSettings["label_barcode2"] + "";
                checkCuplicate = ConfigurationManager.AppSettings["checkCuplicate"] + "";
                searchModel.Text = ConfigurationManager.AppSettings["searchModel"] + "";
                cmb_printType = ConfigurationManager.AppSettings["cmb_printType"] + "";
                sp1.PortName = ConfigurationManager.AppSettings["PortName"] + "";
                sp1.BaudRate = Convert.ToInt32(ConfigurationManager.AppSettings["BaudRate"] + "");
                sp1.DataBits = Convert.ToInt32(ConfigurationManager.AppSettings["DataBits"] + "");
                sp1.DataReceived += new SerialDataReceivedEventHandler(sp1_DataReceived);
                //sp1.ReceivedBytesThreshold = 1;
                //准备就绪              
                sp1.DtrEnable = true;
                sp1.RtsEnable = true;
                //设置数据读取超时为1秒
                sp1.ReadTimeout = 1000;

                try
                {
                    switch (skin)
                    {
                        case 0: styleManager1.ManagerStyle = eStyle.Office2007Blue; break;
                        case 1: styleManager1.ManagerStyle = eStyle.Office2007Silver; break;
                        case 2: styleManager1.ManagerStyle = eStyle.Office2007Black; break;
                        case 3: styleManager1.ManagerStyle = eStyle.Office2007VistaGlass; break;
                        case 4: styleManager1.ManagerStyle = eStyle.Office2010Blue; break;
                        case 5: styleManager1.ManagerStyle = eStyle.Office2007Silver; break;
                        case 6: styleManager1.ManagerStyle = eStyle.Office2010Black; break;
                        case 7: styleManager1.ManagerStyle = eStyle.VisualStudio2010Blue; break;
                        case 8: styleManager1.ManagerStyle = eStyle.Windows7Blue; break;
                        default: styleManager1.ManagerStyle = eStyle.Office2007Blue; break;//默认的 
                    }
                }
                catch (Exception)
                {

                    throw;
                }

                if (print1Flag)
                {
                    if (!File.Exists(TemplatePath))
                    {
                        MessageBox.Show("勾选模板1，但是文件不存在，请重新选择模板文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    if (string.IsNullOrEmpty(comboBox_printer1))
                    {
                        MessageBox.Show("打印机1需要选择", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                if (print2Flag)
                {
                    if (!File.Exists(TemplatePath2))
                    {
                        MessageBox.Show("勾选模板2，但是文件不存在，请重新选择模板文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    if (string.IsNullOrEmpty(comboBox_printer2))
                    {
                        MessageBox.Show("打印机2需要选择", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
            }

        }
        #endregion


        private void btn_scan_Click(object sender, EventArgs e)
        {
            t_Adderss.Text = "";
            SwitchToLanguageMode("en-US");
            //控制键盘大写
            SetState(VirtualKeys.VK_CAPITAL, true);
            // 记录搜索开始时间
            _searchStartTime = DateTime.Now; 
            try
            {
                if (!sp1.IsOpen)
                {
                    sp1.Open();
                }
                if (sp1.IsOpen)
                {
                    sp1.Write("AT+SCAN?");
                }                
            }
            catch (Exception ex)
            {
                MessageBox.Show("串口发送异常"+ex.ToString());
            }
            //Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //config.AppSettings.Settings["GetDeviceAddress"].Value = "";
            //config.Save();

            dataGridView1.DataSource = null;
            builder.Clear();
            _info.Text = "";
            // 检查循环搜索复选框是否选中
            if (checkBoxX1.Checked)
            {
                isLoopSearching = true;
                timerLoopSearch.Start(); // 启动定时器
            }
        }

        

        private void SwitchToLanguageMode(string cultureType)
        {
            var installedInputLanguages = InputLanguage.InstalledInputLanguages;

            if (installedInputLanguages.Cast<InputLanguage>().Any(i => i.Culture.Name == cultureType))
            {
                InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(System.Globalization.CultureInfo.GetCultureInfo(cultureType));
            }
        }

        #region 串口通讯
        string str_DataReceive = "";
        StringBuilder builder = new StringBuilder();
        private delegate void DisplayDelegate(String ReceiveData);
        private DisplayDelegate displayDelegate;
        //绑定委托方法
        //private displayDelegate new DisplayDelegate(ReceiveDataHandle);
        private void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                System.Threading.Thread.Sleep(150);
                str_DataReceive = sp1.ReadExisting();
                //让子线程告诉窗体线程来完成相应的控件操作。
                this.Invoke((EventHandler)(delegate
                {
                    if (string.IsNullOrEmpty(str_DataReceive))
                    {
                        //richTextBox1.Text = str_DataReceive;
                    }
                    else
                    {                       
                        try
                        {
                            //Console.WriteLine(str_DataReceive);
                            if (!str_DataReceive.Contains("Devices Found"))
                            {
                                builder.Append(str_DataReceive);
                            }
                            else 
                            {
                                builder.Append(str_DataReceive);
                                Console.WriteLine(builder.ToString());
                                WriteLogTools.WriteDebug("builder:");
                                WriteLogTools.WriteDebug(builder.ToString());
                                List<Device> devices = reFormat(builder.ToString());

                                // 计算搜索耗时（毫秒）
                                TimeSpan searchDuration = DateTime.Now - _searchStartTime;  // 新增这行
                                double elapsedMs = searchDuration.TotalMilliseconds;       // 新增这行

                                // 筛选 type 等于 "tp922" 的设备，并按 value 排序
                                List<Device> filteredAndSortedDevices;
                                // 当searchModel为空时显示所有设备，否则按类型筛选
                                if (string.IsNullOrEmpty(searchModel.Text?.Trim()))
                                {
                                    // 显示所有设备并按信号强度降序排序
                                    filteredAndSortedDevices = devices
                                        .OrderByDescending(d => d.Value)
                                        .ToList();
                                    _info.Text = $"搜索到 {filteredAndSortedDevices.Count} 个设备，耗时 {elapsedMs:F1} 毫秒";  // 修改此行
                                }
                                else
                                {
                                    filteredAndSortedDevices = devices
                                        .Where(d => d.Type == searchModel.Text)
                                        .OrderByDescending(d => d.Value)
                                        .ToList();
                                    _info.Text = $"搜索到 {filteredAndSortedDevices.Count} 个 {searchModel.Text} 设备，耗时 {elapsedMs:F1} 毫秒";
                                }

                                // 绑定数据到DataGridView
                                dataGridView1.DataSource = filteredAndSortedDevices;
                                builder.Clear();

                                // 搜索到设备后停止循环搜索（保持原有逻辑）
                                if (filteredAndSortedDevices.Count > 0)
                                {
                                    isLoopSearching = false;
                                }
                               


                                // 获取筛选和排序后设备列表中第0个设备的Address值
                                string firstDeviceAddress = string.Empty;
                                if (filteredAndSortedDevices.Any()) // 检查列表是否包含元素以避免索引超出范围异常
                                {
                                    firstDeviceAddress = filteredAndSortedDevices[0].Address;
                                }
                                if (!string.IsNullOrEmpty(firstDeviceAddress))
                                {
                                   
                                    //if (cmb_Separator == 0)
                                    //{
                                    //    firstDeviceAddress = firstDeviceAddress.Replace("-","").Replace("-", "");
                                    //}
                                    //if (cmb_Separator == 1)
                                    //{
                                    //    firstDeviceAddress = FormatMacAddress(firstDeviceAddress, ':');
                                    //}
                                    //if (cmb_Separator == 2)
                                    //{
                                    //    firstDeviceAddress = FormatMacAddress(firstDeviceAddress, '-');
                                    //}
                                    firstDeviceAddress = FormatMacAddress(firstDeviceAddress, ":");

                                    t_Adderss.Text = firstDeviceAddress;
                                    //getDeviceAddress = firstDeviceAddress;


                                    //判断重复
                                    if (checkCuplicate == "Y")
                                    {
                                        string sql = $@"select * from  print_rec where sn='{firstDeviceAddress}' and status=1";
                                        DataTable dt = DBhelper.SelectDataBase(sql);
                                        if (dt.Rows.Count > 0)
                                        {
                                            string create_time = dt.Rows[0]["create_time"] + "";
                                            string msg = $@"该SN：{firstDeviceAddress}已经在{create_time}打印过，如需再打印，需要先失效原有记录";
                                            _info.Text = msg;
                                            MessageBoxEx.Show(msg);
                                            return;
                                        }
                                    }

                                    // 缓存数据
                                    var cache = MemoryCacheSingleton.Instance;
                                    cache.Set("getDeviceAddress", firstDeviceAddress, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(10)));
                                    //var value = cache.Get("getDeviceAddress");

                                    //打印状态--镭雕/标签打印
                                    bool print_ok = false;

                                    if (cmb_printType == "标签打印") 
                                    {
                                        //打印
                                        if (barTender == null)
                                        {
                                            barTender = new BarTender_Print();
                                        }            

                                        if (print1Flag)
                                        {
                                            Hashtable PrintDataHashtable = new Hashtable();//待打印的内容
                                            PrintDataHashtable.Add("sn", firstDeviceAddress);//获得
                                            print_ok = barTender.Print2(TemplatePath, PrintDataHashtable, 1, comboBox_printer1);
                                            WriteLogTools.WriteMessage($"打印的内容:{firstDeviceAddress}");
                                        }
                                    }
                                    if (cmb_printType == "镭雕打印")
                                    {
                                        //执行模拟键鼠
                                        this.Hide();
                                        Thread.Sleep(300);
                                        WriteLogTools.WriteMessage("------------------RunTest-----------------------");
                                        threadPause = new Thread(RunTest);
                                        threadPause.Start();
                                        this.Show();
                                        print_ok = true;
                                        _info.Text = $"镭雕成功！\r\n {firstDeviceAddress}  ";
                                    }
                                    if (print_ok)
                                    {
                                        _info.Text = $"打印成功！\r\n {firstDeviceAddress}  ";
                                        string ins = $@"INSERT INTO print_rec
                                            (
                                            sn
                                            ,model
                                             ,create_by
                                             ,create_time
                                            )
                                            VALUES
                                            (
 
                                             '{firstDeviceAddress}' 
                                             ,'{searchModel.Text}' 
                                             ,'' -- create_by - VARCHAR(64)
                                             ,NOW() -- create_time - DATETIME
                                            );";
                                        int res = DBhelper.ExecuteSql(ins);
                                        if (res <= 0)
                                        {
                                            _info.Text = $"数据库写入失败，请联系管理员";
                                        }
                                    }
                                    


                                }
                            }

                        }
                        catch (Exception ex)
                        {
                            WriteLogTools.WriteMessage("ex" + ex.Message);
                            //MessageBox.Show(ex.Message);
                        }

                    }
                }));

            }
            catch (Exception)
            {
                // MessageBox.Show(ex.Message);
                try
                {
                    //label_重量值.Text = 0.0 + "";
                }
                catch (Exception)
                {

                }

            }
        }
        #endregion


        private void RunTest()
        {
            string filename = "默认示教.MKF";
            List<string> cfg= new List<string>();
            try
            {
                using (StreamReader reader = new StreamReader(filename))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                        cfg.Add(line);
                    }
                }
            }
            catch (IOException e)
            {
                Console.WriteLine("An IO exception has been thrown!");
                Console.WriteLine(e.ToString());
            }
            //测试按钮，测试当前列表中的命令是否可以成功执行

            string[] result = new string[cfg.Count];
            try
            {
                for (int i = 0; i < cfg.Count; i++)
                {
                    if (MoseKeyboard.ExcuteCmd(cfg[i].ToString()) == true)
                    {
                        result[i] = "执行命令成功：" + cfg[i].ToString();
                        //StatusLabel.Text = result[i];
                        WriteLogTools.WriteMessage(result[i]);
                    }
                    else
                    {
                        result[i] = "执行命令失败：" + cfg[i].ToString();
                        WriteLogTools.WriteMessage(result[i]);
                    }

                    //if (MoseKeyboard.GetState(KeyBord.NumLock) == true)//判断numLock
                    //    label1.ForeColor = Color.Green;
                    //else
                    //    label1.ForeColor = Color.DarkGray;
                    //if (MoseKeyboard.GetState(KeyBord.CapsLock) == true)
                    //    label2.ForeColor = Color.Green;
                    //else
                    //    label2.ForeColor = Color.DarkGray;
                    //if (MoseKeyboard.GetState(KeyBord.Scroll) == true)
                    //    label3.ForeColor = Color.Green;
                    //else
                    //    label3.ForeColor = Color.DarkGray;
                }
                //File.WriteAllLines(filename, result);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private List<Device> reFormat(string input)
        {
            // 示例输入:
            // Scanning...
            // 0: 0xF19A0D2E75E3, -66, TP357S(75E3)
            // Devices Found: 1
            List<Device> devices = new List<Device>();
            if (string.IsNullOrEmpty(input))
                return devices;
            try
            {
                // 1. 清除空行并按行分割（保留原始行结构便于解析）
                var lines = input.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
                                .Select(line => line.Trim())
                                .Where(line => !string.IsNullOrEmpty(line));

                // 2. 过滤出设备信息行（排除Scanning...和Devices Found行）
                var deviceLines = lines.Where(line =>
                    Regex.IsMatch(line, @"^\d+:\s*[0-9A-Fa-fx]+,\s*-?\d+,\s*[A-Za-z0-9]+\(?.*\)?$")
                ).ToList();

                // 3. 正则匹配设备信息（支持类型与括号间有无空格）
                var devicePattern = new Regex(
                    @"^\d+:\s*0x([0-9A-Fa-f]+),\s*(-?\d+),\s*([A-Za-z0-9]+)\s*\(?[0-9A-Fa-f]*\)?$",
                    RegexOptions.IgnoreCase
                );

                foreach (var line in deviceLines)
                {
                    var match = devicePattern.Match(line);
                    if (match.Success && match.Groups.Count == 4)
                    {
                        // 提取地址（已去除0x前缀）
                        string address = match.Groups[1].Value.Trim().ToUpper();

                        // 提取信号强度（确保转换成功）
                        if (int.TryParse(match.Groups[2].Value.Trim(), out int rssi))
                        {
                            // 提取设备类型
                            string type = match.Groups[3].Value.Trim().ToUpper();

                            devices.Add(new Device
                            {
                                Address = address,
                                Value = rssi,
                                Type = type
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLogTools.WriteDebug($"解析设备信息失败: {ex.Message}");
            }

            return devices;
        }

        // 设备模型类
        public class Device
        {
            public string Address { get; set; }  // 设备地址（不含0x前缀）
            public int Value { get; set; }       // 信号强度（RSSI值）
            public string Type { get; set; }     // 设备类型（如TP357S）
        }

        //class Device
        //{
        //    public int Index { get; }
        //    public string Address { get; }
        //    public int Value { get; }
        //    public string Type { get; }

        //    public Device(int index, string address, int value, string type)
        //    {
        //        Index = index;
        //        Address = address;
        //        Value = value;
        //        Type = type;
        //    }
        //}

        #region 控制键盘大小写


        public static bool GetState(VirtualKeys Key)
        {
            return (GetKeyState((int)Key) == 1);
        }
        public static void SetState(VirtualKeys Key, bool State)
        {
            if (State != GetState(Key))
            {
                keybd_event((byte)Key, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0);
                keybd_event((byte)Key, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
            }
        }
        #endregion
        private void Form1_Load(object sender, EventArgs e)
        {
            //控制键盘大写
            SetState(VirtualKeys.VK_CAPITAL, true);

            #region 启动后去右下角待着
            int x = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Size.Width - this.Width;
            int y = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Size.Height - this.Height;
            this.SetDesktopLocation(x, y);
            #endregion

            ReadConfig();//载入配置方法；

            barTender = new BarTender_Print();
            string conn = ConfigurationManager.AppSettings["Connectionstring"] + "";
            DBhelper = new MySQLHelper(conn);
            //timer_chk_py.Start();
            //timer1.Start();
            //_试用软件();
            //timer2.Start();
            searchModel.Enabled = true;
            searchModel.BackColor = Color.FromArgb(192, 255, 192);
            //searchModel.Clear();
            //model.Text = "";
            searchModel.Focus();
            _Stand_BY();

            // 初始化定时器
            timerLoopSearch = new System.Windows.Forms.Timer();
            timerLoopSearch.Interval = 1000; // 设置间隔为 2 秒
            timerLoopSearch.Tick += TimerLoopSearch_Tick;

            t_Adderss.Focus();

        }


        private void TimerLoopSearch_Tick(object sender, EventArgs e)
        {
            if (isLoopSearching)
            {
                try
                {
                    if (!sp1.IsOpen)
                    {
                        sp1.Open();
                    }
                    if (sp1.IsOpen)
                    {
                        sp1.Write("AT+SCAN?");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("循环搜索出错：" + ex.ToString());
                    isLoopSearching = false;
                    timerLoopSearch.Stop(); // 停止定时器
                }
            }
        }

        /// <summary>
        /// byte[]转为16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ByteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }


        #region panel颜色变化
        //panel颜色变化
        private void NG_BackColor()
        {
            for (int i = 0; i < 3; i++)
            {
                panelEx1.Style.BackColor2.Color = Color.FromArgb(175, 210, 255);
                Thread.Sleep(100);
                panelEx1.Style.BackColor2.Color = Color.Red;
                Thread.Sleep(100);
            }
        }
        //panel颜色变化
        private void PASS_BackColor()
        {
            for (int i = 0; i < 2; i++)
            {
                panelEx1.Style.BackColor2.Color = Color.FromArgb(175, 210, 255);
                Thread.Sleep(200);
                panelEx1.Style.BackColor2.Color = Color.Green;
                Thread.Sleep(200);
            }
        }
        #endregion

      

        #region 试用软件
        public void _试用软件()
        {
            try
            {
                //判断软件是否注册
                RegistryKey retkey = Registry.CurrentUser.OpenSubKey("SOFTWARE", true).CreateSubKey("Matter_Barcode").CreateSubKey("Register.INI");
                foreach (string strRNum in retkey.GetSubKeyNames())
                {
                    if (strRNum == softReg.GetRNum())
                    {
                        this.Text += "  [已注册]";
                        注册ToolStripMenuItem.Visible = false;
                        //this.labRegInfo.Text = "此软件已注册！";
                        //this.btnReg.Enabled = false;
                        return;
                    }
                }
                this.Text += "  [未注册]";
                //this.labRegInfo.Text = "此软件尚未注册！";
                //this.btnReg.Enabled = true;
                MessageBox.Show("您现在使用的是试用版，可以免费试用30次！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);

                Int32 tLong;    //已使用次数
                try
                {
                    tLong = (Int32)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Matter_Barcode", "UseTimes", 0);
                    MessageBox.Show("您已经使用了" + tLong + "次！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch
                {
                    MessageBox.Show("欢迎使用本软件！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Matter_Barcode", "UseTimes", 0, RegistryValueKind.DWord);
                }
                //判断是否可以继续试用
                tLong = (Int32)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Matter_Barcode", "UseTimes", 0);
                if (tLong < 30)
                {
                    int tTimes = tLong + 1;
                    Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Matter_Barcode", "UseTimes", tTimes);
                }
                else
                {
                    DialogResult result = MessageBox.Show("试用次数已到！您是否需要注册？", "信息", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                    if (result == DialogResult.Yes)
                    {
                        FormRegister.state = false; //设置软件状态为不可用
                        this.Hide();
                        FormRegister form = new FormRegister();
                        form.Show();

                        //btnReg_Click(sender, e);    //打开注册窗口
                    }
                    else
                    {
                        Application.ExitThread();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("请以管理员身份运行!" + ex.Message);
                this.Close();
            }

        }
        #endregion

        private void buttonX1_Click(object sender, EventArgs e)
        {
            string sn;
            if (!cache.TryGetValue("getDeviceAddress", out sn))
            {
                Console.WriteLine("Cache item expired.");
            }
            PASS_OR_NG.Text = "";
            _info.Text = "";
            //panelEx1.BackColor = Color.Azure;
            panelEx1.Style.BackColor2.Color = Color.FromArgb(175, 210, 255);
            //model.Clear();
            //t_Manualcode.Clear();
            //model.Focus();
        }

        private void 数据查看ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Frm_Data frm = new Frm_Data();
            frm.Show();
        }

        private void 条码数据库ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Input_Excel frm = new Input_Excel();
            frm.Show();
        }

        private void 条码校验ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            string pwd= ConfigurationManager.AppSettings["SetupPwd"];
            InputDialog f = new InputDialog();
            f.Text = "请输入密码";
            f.textBox1.PasswordChar = '*';
            if (f.ShowDialog() == DialogResult.OK)
            {
                string input = f.textBox1.Text;
                if (pwd == input)
                {
                    Setup frm = new Setup();
                    frm.Show();
                }
                else {
                    Tools.ShowError("密码错误");
                    return;
                }
            }
            else
            {              
                return;
            }
        }


        static string FormatMacAddress(string mac,string sp_char)
        {
            // 检查输入字符串的长度是否为12个字符（MAC地址应为6个字节，即12个十六进制字符）
            if (mac.Length != 12)
            {
                throw new ArgumentException("MAC地址应为12个字符长。");
            }
            // 利用字符串插值和Substring方法，每两个字符插入一个短横线
            return $"{mac.Substring(0, 2)}{sp_char}{mac.Substring(2, 2)}{sp_char}{mac.Substring(4, 2)}{sp_char}{mac.Substring(6, 2)}{sp_char}{mac.Substring(8, 2)}{sp_char}{mac.Substring(10, 2)}";
        }


        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox1 frm = new AboutBox1();
            frm.Show();
        }

        private void 注册ToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
        }

        private void exitMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult TS = MessageBox.Show("您确认要退出系统吗？", "系统消息", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (TS == DialogResult.Yes)
            {
                // e.Cancel = false;
                // Application.Exit();
                Application.ExitThread();
            }
            else
            {
                //e.Cancel = true;
            }
        }

        //public void _插入数据(string model, string demoSN, string iSN, string _是否合格, string _批次号, string _作业员)
        //{
        //    OleDbConnection con = new OleDbConnection(ConStr);
        //    con.Open();
        //    string Operation_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        //    string sql = $@"INSERT INTO data(model,mac1,mac2,Operation_time,iCheck_sta,BILL_NO,CREATE_BY) 
        //    values('{model}','{demoSN}','{iSN}','{Operation_time}','{_是否合格}','{_批次号}','{_作业员}') ";
        //    OleDbCommand cmd = new OleDbCommand(sql, con);
        //    cmd.ExecuteNonQuery();
        //    con.Close();
        //}

        int _该条码已经对比次数;
        int _该条码最大可对比次数;
        int _已校验次数;
        private void MT_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData != Keys.Enter)
            {
                return;
            }

            if (searchModel.Text.Trim() == "")
            {
                return;
            }
            Stopwatch stopwatch = Stopwatch.StartNew();
            #region 条码规则校验
            if (!string.IsNullOrEmpty(barcodeRule))
            {
                string reson = "";
                if (!Tools.CheckBarcodeByRule(searchModel.Text, barcodeRule, out reson))
                {
                    _info.Text = reson;
                    _NG处理(reson);
                    searchModel.SelectAll();
                    searchModel.Focus();
                    return;
                }
            }
            if (checkCuplicate == "Y")
            {
                DataTable dt = DBhelper.SelectDataBase($"select * from matter_print_rec where qrcode='{searchModel.Text}' and status=1 ");
                if (dt.Rows.Count > 0)
                {
                    string msg = $"{searchModel.Text}已经在\r\n {dt.Rows[0]["create_time"] + ""}打印过，\r\n 不能重复扫描打印";
                    _NG处理(msg);
                    return;
                }
            }
           
            #endregion
            PASS_OR_NG.Text = "";
            _info.Text = "";

            // 要传递给exe的参数  
            string arguments = searchModel.Text;
            if (!arguments.StartsWith("MT:"))
            {
                arguments = "MT:" + arguments;
            }
            string formattedNumber = "";
            
            Entity.manualData manual = JsonConvert.DeserializeObject<manualData>(formattedNumber);
            if (manual.pid == 0) 
            {
                _NG处理("pid不正确");
                return;
            }
            t_Adderss.Text = manual.manual_code;
            if (barTender == null)
            {
                barTender = new BarTender_Print();
            }
            bool print_ok=false;
           
            if (print1Flag)
            {
                Hashtable PrintDataHashtable = new Hashtable();//待打印的内容
                PrintDataHashtable.Add("qrcode", searchModel.Text);//获得
                PrintDataHashtable.Add("manualcode", manual.manual_code);//获得
                print_ok = barTender.Print2(TemplatePath, PrintDataHashtable, 1, comboBox_printer1);
                WriteLogTools.WriteMessage($"打印1的内容:{searchModel.Text},{manual.manual_code}");
            }
            if (print2Flag) 
            {
                //匹配本地的pid和vid
                //pid转16进制
                string pid_hex = "0x" + manual.pid.ToString("X");
                string vid_hex = "0x" + manual.vid.ToString("X");
                DataTable pn_dt = DBhelper.SelectDataBase($"select pn from matter_product_code where pid='{pid_hex}' and  vid='{vid_hex}' ");
                if (pn_dt == null || pn_dt.Rows.Count <= 0)
                {
                    _NG处理($"找不到产品PN！pid:{pid_hex}，vid:{vid_hex},请先维护");
                    return;
                }
                string pn = pn_dt.Rows[0][0] + "";
                if (pn == null || pn == "")
                {
                    _NG处理($"产品PN不能为空");
                    return;
                }
                //https://matter.ikea.com/v1/add/?r=E2490,MT:Y.K9042C00KA0648G00

                Hashtable PrintDataHashtable = new Hashtable();//待打印的内容
                string url = ConfigurationManager.AppSettings["urlPrefix"];
                string qr = string.Format(url,pn, searchModel.Text.Trim());
                PrintDataHashtable.Add("qrcode", qr);//获得
                PrintDataHashtable.Add("manualcode", manual.manual_code);//获得
                print_ok = barTender.Print2(TemplatePath2, PrintDataHashtable, 1, comboBox_printer2);
                WriteLogTools.WriteMessage($"打印2的内容:{qr},{manual.manual_code}");
            }
           
           
            if (print_ok)
            {
                _info.Text = $"打印成功！\r\n {ConfigurationManager.AppSettings["label_barcode1"]}{searchModel.Text} \r\n {ConfigurationManager.AppSettings["label_barcode2"]}{t_Adderss.Text}  ";
                string ins = $@"INSERT INTO matter_print_rec
                    (
                     qrcode
                     ,manualcode
                     ,manualcode_type
                     ,create_by
                     ,create_time
                    )
                    VALUES
                    (
 
                     '{searchModel.Text}' -- qrcode - VARCHAR(50)
                     ,'{t_Adderss.Text}' -- manualcode - VARCHAR(255)
                     ,'{cmb_Separator}' -- cmb_Separator - VARCHAR(10)
                     ,'' -- create_by - VARCHAR(64)
                     ,NOW() -- create_time - DATETIME
                    );";
                int res = DBhelper.ExecuteSql(ins);
                if (res <= 0)
                {
                    _info.Text = $"数据库写入失败，请联系管理员";
                }
            }
            stopwatch.Stop(); // 停止计时器
            //label_ct.Text = stopwatch.ElapsedMilliseconds + "ms";
            _PASS处理();

            searchModel.Clear();
            t_Adderss.Clear();
            searchModel.Focus();

        
        }


        //创建GET的HTTP请求 
        public string GetRequest(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                //request.ContentType = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/json";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream rs = response.GetResponseStream();
                //StreamReader sr = new StreamReader(rs, encode);
                StreamReader sr = new StreamReader(rs, Encoding.UTF8);
                var result = sr.ReadToEnd();
                sr.Close();
                rs.Close();
                return result;
            }
            catch (Exception ex)
            {
                return ex.Message;

            }

        }

        int trySec = 0;
        private void timer2_Tick(object sender, EventArgs e)
        {
            trySec++;
            if (trySec > 10)
            {
                timer2.Stop();
                //_试用软件();
            }

        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Frm_Model frm = new Frm_Model();
            frm.Show();
        }

        private void Manualcode_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void panelEx3_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void Frm_main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (sp1.IsOpen)
            {
                sp1.Close();
            }
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //修改配置节点AppSettings的内容     
            config.AppSettings.Settings["searchModel"].Value = searchModel.Text;

            //保存配置文件
            config.Save();

        }

        private void 示教编程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            robotstudio frm = new robotstudio();
            frm.Show();
        }






        #region 强制扫描模式
        DateTime _dt = DateTime.Now;

        private void timer_chk_py_Tick(object sender, EventArgs e)
        {
            
        }
       

        private void 注册ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            FormRegister f = new FormRegister();
            f.Show();
        }

        private void t_SN1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (_ONLY_SCAN == "Checked")
            {
                DateTime tempDt = DateTime.Now;          //保存按键按下时刻的时间点
                TimeSpan ts = tempDt.Subtract(_dt);     //获取时间间隔
                if (ts.Milliseconds > 50)//判断时间间隔，如果时间间隔大于50毫秒，则将TextBox清空
                {
                    t_Adderss.Text = "";
                }
                _dt = tempDt;
            }
        }
        #endregion

        #region 计算百分比
        private string res = "0.00%";
        public string getDacl(string A, string B)
        {
            if (string.IsNullOrEmpty(A))
            {
                A = "0";
            }
            if (string.IsNullOrEmpty(B))
            {
                B = "0";
            }
            if (B.Equals("0"))
            {
                return res;
            }
            else
            {
                double A1 = Convert.ToDouble(A);
                double B1 = Convert.ToDouble(B);
                double C = A1 / B1 * 100;
                res = C.ToString("f2") + "%";
            }
            return res;
        }
        #endregion

        #region _NG处理
        public void _NG处理(string info)
        {
            WriteLogTools.WriteMessage("NG处理:"+ info);
            PASS_OR_NG.Text = "NG";
            PASS_OR_NG.ForeColor = Color.White;
            _info.Font = new System.Drawing.Font("微软雅黑", 25);
            _info.ForeColor = Color.Red;
            _info.Text = info;
            Thread thread = new Thread(new ThreadStart(NG_BackColor));
            thread.Start();//NG闪背景

            //_总数量.Text = (Convert.ToInt32(_总数量.Text) + 1).ToString();
            //_NG数量.Text = (Convert.ToInt32(_NG数量.Text) + 1).ToString();
            //lab_NG_lv.Text = getDacl(_NG数量.Text, _总数量.Text);//计算百分比
            //lab_Pass_lv.Text = getDacl(_ok数量.Text, _总数量.Text);//计算百分比
            if (ConfigurationManager.AppSettings["SoundPlayerNG"] == "True")
            {
                SoundPlayer sp = new SoundPlayer(NGSoundFilePath);
                sp.Play();
            }            
            if (handleError == 0)
            {
            }
            else if (handleError == 1)
            {
                //手动弹窗
                Frm_Fail frm_Fail = new Frm_Fail();
                frm_Fail.label2.Text = info;
                frm_Fail.ShowDialog();
            }
            else if (handleError == 2)
            {
                Frm_Unlock frm = new Frm_Unlock();
                frm.label2.Text = info;
                frm.ShowDialog();
                if (frm.Submit.DialogResult != DialogResult.OK)
                {

                }
            }
            searchModel.SelectAll();
            searchModel.Focus();
        }
        #endregion

        #region _PASS处理
        public void _PASS处理()
        {
            Thread thread2 = new Thread(new ThreadStart(PASS_BackColor));
            thread2.Start();//闪背景           
            _info.ForeColor = Color.Green;
            PASS_OR_NG.Text = "PASS";
            PASS_OR_NG.ForeColor = Color.White;
            t_Adderss.SelectAll();
            if (ConfigurationManager.AppSettings["SoundPlayerOK"] == "True")
            {
                SoundPlayer sp = new SoundPlayer(OKSoundFilePath);
                sp.Play();
            }          
            //_总数量.Text = (Convert.ToInt32(_总数量.Text) + 1).ToString();
            //_ok数量.Text = (Convert.ToInt32(_ok数量.Text) + 1).ToString();
            //lab_NG_lv.Text = getDacl(_NG数量.Text, _总数量.Text);//计算百分比
            //lab_Pass_lv.Text = getDacl(_ok数量.Text, _总数量.Text);//计算百分比
        }
        #endregion _PASS处理


        #region Stand_BY处理
        public void _Stand_BY()
        {
            _info.ForeColor = Color.Black;
            PASS_OR_NG.Text = "";
            PASS_OR_NG.ForeColor = Color.Transparent;
            searchModel.Focus();
        }
        #endregion Stand_BY处理

        private void T_demo_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {

        }

        private void t_SN1_TextChanged(object sender, EventArgs e)
        {

        }










    }
}
